package com.zhuss.core.processor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.zhuss.bean.bo.core.user.CreateUserBo;
import com.zhuss.bean.vo.core.DetailImportVo;
import com.zhuss.common.AbstractBo;
import com.zhuss.common.ResponseSucc;
import com.zhuss.core.db.dao.ext.TempDao;
import com.zhuss.core.db.entity.Company;
import com.zhuss.core.db.entity.Role;
import com.zhuss.core.db.entity.Temp;
import com.zhuss.core.db.entity.User;
import com.zhuss.enums.ImportType;
import com.zhuss.enums.IsEnum;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.ExcelUtil;
import com.zhuss.util.NoUtil;
import com.zhuss.util.PingYinUtil;
import com.zhuss.util.UserUtil;

@Component("userImport2")
public class UserImport2 {
	
	@Autowired
	@Qualifier("companyRead")
	private CompanyRead companyRead;
	
	@Autowired
	@Qualifier("userRead")
	private UserRead userRead;
	
	@Autowired
	@Qualifier("roleRead")
	private RoleRead roleRead;
	
	@Autowired
	private UserCreate userCreate;
	
	@Autowired
	private TempDao tempDao;
	
	
	@Value("${filePath}")
    private String filePath;
	
	@Value("${fileReadPath}")
	private String fileReadPath;

	public Object process(MultipartFile file, List<String[]> resultList, Integer type) throws Exception {
		String url = "";
		String path = filePath + "batch\\user\\";
		String readPath = fileReadPath +  "batch\\user\\";
		String fileName = "";
		if (ImportType.导入.sameKey(type)) {
			
			byte[] list = file.getBytes();
			File file2 = new File(path);
			if (!file2.exists()) {
				file2.mkdirs();
			}
			fileName = NoUtil.gen();
			file2 = new File(path + "用户导入-" + fileName + ".xls");
			FileOutputStream file3 = new FileOutputStream(file2);
			file3.write(list);
			file3.close();
			
			AbstractBo abstractBo = new AbstractBo();
			Integer area = abstractBo.getConcurrentArea();
			
			List<Temp> tempList = new ArrayList<Temp>();
			
			String batchNubmer = NoUtil.gen();
			Date now = new Date();
	    	Map<String, Integer> userTypeMap = UserUtil.getUserTypeMap();
	    	Map<String, Integer> sexMap = UserUtil.getSexMap();
	    	Map<String, Company> companyMap = companyRead.listMap(area);
	    	Map<String, Role> roleMap = roleRead.listMap(area);
	    	
	    	outer:
	    	for (int i = 0; i < resultList.size(); i ++) {
	    		if (i == 0) {
	    			continue;
	    		}
	    		String[] item = resultList.get(i);
	    		
	    		String item0 = item[0];
	    		String item1 = item[1];
	    		String item2 = item[2];
	    		String item3 = item[3];
	    		String item4 = item[4];
	    		String item5 = item[5];
	    		String item6 = item[6];
	    		String item7 = item[7];
	    		
	    		
	    		Temp temp = new Temp();
				temp.setItem0(item0);
				temp.setItem1(item1);
				temp.setItem2(item2);
				temp.setItem3(item3);
				temp.setItem4(item4);
				temp.setItem5(item5);
				temp.setItem6(item6);
				temp.setItem7(item7);
				temp.setAccount(abstractBo.getConcurrentUserName());
				temp.setBatchNumber(batchNubmer);
				temp.setCreateTime(now);
				
	    		
	    		
	    		String name = item0;
	    		String username = item1;
	    		String userTypeName = item2;
	    		String compName = item3;
	    		String roleName = item4;
	    		String sexName = item5;
	    		String ageName = item6;
	    		String phone = item7;
	    		
	    		if (name == null || "".equals(name.trim())) {
	    			temp.setReason(ExceptionCode.姓名为空.getMsg() + ": " + name);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		if (userTypeName == null || "".equals(userTypeName.trim())) {
	    			temp.setReason(ExceptionCode.入驻单位为空.getMsg() + ": " + userTypeName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		if (compName == null || "".equals(compName.trim())) {
	    			temp.setReason(ExceptionCode.单位名称为空.getMsg() + ": " + compName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		if (roleName == null || "".equals(roleName.trim())) {
	    			temp.setReason(ExceptionCode.角色为空.getMsg() + ": " + roleName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		if (sexName == null || "".equals(sexName.trim())) {
	    			temp.setReason(ExceptionCode.性别为空.getMsg() + ": " + sexName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		if (phone == null || "".equals(phone.trim())) {
	    			temp.setReason(ExceptionCode.电话为空.getMsg() + ": " + phone);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		
	    		try {
	    			if (ageName != null && !"".equals(ageName.trim())) {
	    				Integer.parseInt(ageName);
	    			}
	    		} catch (NumberFormatException e) {
	    			temp.setReason(ExceptionCode.年龄格式错误.getMsg() + ": " + ageName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		
	    		
	    		
	    		
	    		Integer userType = userTypeMap.get(userTypeName);
	    		
	    		Company company = null;
	    		
	    		company = companyMap.get(compName);
	    		
	    		if (company == null) {
	    			temp.setReason(ExceptionCode.单位不存在.getMsg() + ": " + userTypeName + "-" + compName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		Role role = roleMap.get(roleName);
	    		if (role == null) {
	    			temp.setReason(ExceptionCode.角色不存在.getMsg() + ": " + roleName);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		
	    		Long compId = company.getCompanyId();
	    		Long roleId = role.getRoleId();
	    		Integer sex = sexMap.get(sexName);
	    		Integer age = ageName != null && !"".equals(ageName.trim()) ? Integer.parseInt(ageName) : null;
	    		
	    		List<String> usernameList = new ArrayList<String>();
	    		if (username == null || "".equals(username.trim())) {
	    			usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFirstSpell(name));
	    			char ch = name.charAt(0);
	    			String family = String.valueOf(ch);
	    			String[] strList = name.split(family);
	    			String name2 = strList[1];
	    			usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFullSpell(family) + PingYinUtil.getFirstSpell(name2));
	    			usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFullSpell(name));
	    			
	    		}
	    		
	    		usernameFor:
	    		for (int j = 0; j < usernameList.size(); j++) {
	    			username = usernameList.get(j);
	    			List<User> existUserList = userRead.list(username);
	    			if (existUserList == null || existUserList.isEmpty()) {
	    				break usernameFor;
	    			}
	    			if (existUserList != null && !existUserList.isEmpty() && j == usernameList.size() - 1) {
	    				temp.setReason(ExceptionCode.账号已存在.getMsg() + ": " + username);
	    				temp.setItem1(username);
	    				tempDao.insert(temp);
	        			tempList.add(temp);
	    				continue outer;
	    			}
	    		}
	    		
	    		CreateUserBo param = new CreateUserBo();
	    		param.setName(name);
	    		param.setUsername(username);
	    		param.setType(userType);
	    		param.setCompanyId(compId);;
	    		param.setRoleIdList(Arrays.asList(roleId));
	    		param.setSex(sex);
	    		param.setAge(age);
	    		param.setPhone(phone);
	    		param.setArea(area);
	    		param.setIsBatch(IsEnum.是.key());
	    		
	    		Object result = userCreate.process(param);
	    		System.out.println(result);
	    		if (result instanceof ResponseSucc) {
	    			String reason = ((ResponseSucc) result).getMsg();
	    			temp.setReason(reason);
	    			tempDao.insert(temp);
	    			tempList.add(temp);
	    			continue;
	    		}
	    		temp.setReason(new ResponseSucc().getCode() + ":" + new ResponseSucc().getMsg());
	    		temp.setItem1(username);
	    		tempList.add(temp);
	    	}
	    	
	    	if (tempList.isEmpty()) {
	    		Temp t = new Temp();
	    		tempList.add(t);
	    	}
	    	
	    	LinkedHashMap<String,String> map = ExcelUtil.getExportUserTempMap();
			File file4 = new File(path + "用户导入-" + fileName + "-结果.xls");
			OutputStream os = new FileOutputStream(file4);
			ExcelUtil.listToExcel(tempList, map, "导入流水表", os);
			
			url = readPath + file4.getName();
	        
		} else {
			
			url = readPath + "用户模板.xls";
			
		}
    	
		DetailImportVo result = new DetailImportVo();
		result.setUrl(url);
        return result;
	}
	
			
}

